package com.winskysoft.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class DatabaseManager {

	private static DatabaseManager databaseManager;

	private Connection con;

	private DatabaseManager(String url, String username, String password)
			throws SQLException, ClassNotFoundException {
		Class.forName("com.mysql.jdbc.Driver");// 注册驱动
		con = DriverManager.getConnection(url, username, password);
	}

	public static DatabaseManager getDatabaseManager(String url,
			String username, String password) throws ClassNotFoundException,
			SQLException {
		databaseManager = new DatabaseManager(url, username, password);
		return databaseManager;
	}

	public static DatabaseManager getDatabaseManager() {
		return databaseManager;
	}

	/**
	 * 查询数据库
	 * 
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	public ResultSet query(String sql) throws SQLException {
		Statement statement = con.createStatement();
		return statement.executeQuery(sql);
	}

	public List<String[]> queryList(String sql) throws SQLException {
		List<String[]> list = new ArrayList<String[]>();
		ResultSet set = query(sql);

		int columnTatol = set.getMetaData().getColumnCount();
		while (set.next()) {
			String[] array = new String[columnTatol];
			for (int i = 1; i <= array.length; i++) {
				array[i - 1] = set.getString(i);
			}
			list.add(array);
		}

		return list;
	}

	public static void main(String[] args) {
		String url = "jdbc:mysql://localhost:3306/rad?useUnicode=true&characterEncoding=UTF-8";
		String username = "root";
		String password = "root";
		try {
			DatabaseManager databaseManager = new DatabaseManager(url,
					username, password);
			List<String[]> set = databaseManager.queryList("show tables;");
			for (String[] s : set) {
				List<String[]> list = databaseManager.queryList("describe "
						+ s[0]);
				for (String[] x : list) {
					for (String str : x) {
						System.out.print(str + "   ");
					}
				}
				System.out.println();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
